package com.qdevelop.model.service.database;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionManager {
	static Logger log = Logger.getLogger(SessionManager.class);

	private static final SessionFactory sessionFactory;
	static {
		try {

			Configuration cfg = new Configuration();
			sessionFactory = cfg.configure().buildSessionFactory();

		} catch (HibernateException ex) {
			log.error("Configuration problem:" + ex.getMessage(), ex);
			throw new RuntimeException("Configuration problem: "
					+ ex.getMessage(), ex);
		}
	}

	@SuppressWarnings("unchecked")
	public static final ThreadLocal session = new ThreadLocal();

	/**
	 * ����session
	 * 
	 * @return Session
	 * @throws HibernateException
	 */
	@SuppressWarnings("unchecked")
	public static Session currentSession() {
		Session s = (Session) session.get();

		if (s == null) {
			try {
				s = sessionFactory.openSession();
				session.set(s);
			} catch (Exception e) {
				log.error("get connection error!", e);
				e.printStackTrace();
			}
		}
		// s.setCacheMode(CacheMode.IGNORE);
		// s.setFlushMode(FlushMode.ALWAYS);
		return s;
	}

	/**
	 * session�ر�
	 * 
	 * @throws HibernateException
	 */
	@SuppressWarnings("unchecked")
	public static void closeSession() {
		if(session!=null){
			Session s = (Session) session.get();
			session.set(null);
			if (s != null)
				try {
					s.close();
				} catch (HibernateException e) {
					log.error("close connection error!", e);
				}
		}
	}
	public static void main(String[] args){
		SessionManager.currentSession();
	}
}
